package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.Manifest;

import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;

import android.os.Bundle;
import android.text.TextUtils;

import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.zhuizikejithreeig.cn.been.LoginBeen;

import com.zhuizikejithreeig.cn.been.MacErrBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.MainActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.AppManager;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.PasswordNameSave;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class LoginActivity extends BasicActivity implements View.OnClickListener {
    private EditText mName1;
    private EditText mName2;
    private Button mName5;
    private TextView mName3;
    private TextView mName4;
    private static final int PHOTO_PERMISS = 100;
    private boolean hasPermission = false;
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_login);
        showBody();

        mName1 = (EditText) findViewById(R.id.name1);
        mName2 = (EditText) findViewById(R.id.name2);
        mName5 = (Button) findViewById(R.id.name5);
        mName3 = (TextView) findViewById(R.id.name3);
        mName4 = (TextView) findViewById(R.id.name4);

        String phone = Utils.getString(ContectUtils.PHONESAVE);
        CompontApplayCation.formLgin = true;
        //当电话号码部位空的时候.说明注册第一步成功,
        if (!TextUtils.isEmpty(phone) && Utils.isPhoneNO(phone)) {

            if (TextUtils.equals(Utils.getString(ContectUtils.STATUS), "2")) {
//                skipOtherActivity(BasicInfoActivity.class, true);
                Intent intent = new Intent(LoginActivity.this, BasicInfoActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            } else {
                skipOtherActivity(MainActivity.class, true);
                finish();
            }
        } else {
            //账号密码进行回显
            hasPermission();
            if (Utils.sdIsOk() || hasPermission) {
                String[] strings = PasswordNameSave.readPassword(LoginActivity.this);
                mName1.setText(strings[0]);
                mName2.setText(strings[1]);
            }
        }
        mName5.setOnClickListener(this);
        mName3.setOnClickListener(this);
        mName4.setOnClickListener(this);
    }


    private void hasPermission() {
        PermissionGen.with(LoginActivity.this)
                .addRequestCode(PHOTO_PERMISS)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = PHOTO_PERMISS)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = PHOTO_PERMISS)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;
        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.name5:
                String pho = mName1.getText().toString().trim();
                String paw = mName2.getText().toString().trim();
                if (pho.isEmpty()) {
                    ToastMake.showToast(getResources().getString(R.string.string51));
                    return;
                }
                if (paw.isEmpty()) {
                    ToastMake.showToast(getResources().getString(R.string.string53));
                    return;
                }
                if (pho.length() != 11) {
                    ToastMake.showToast("电话号码输入的长度有误");
                    return;
                }

                if (Utils.isMobileNO(mName1.getText().toString().trim()) || Utils.everyPaw(mName2.getText().toString().trim())) {
                    //TODO:可以进行登录

                    if (isConnected()) {
                        logIn(pho, paw);
                    } else {
                        ToastMake.showToast(getResources().getString(R.string.string57));
                    }
                }
                break;
            case R.id.name3:
                startActivity(new Intent(LoginActivity.this, RegistActivity.class));
                break;
            case R.id.name4:
                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                break;
        }
    }


    //进行登陆操做
    private void logIn(final String phoneNumber, final String passWord) {
        if (phoneNumber.length() != 11) {
            ToastMake.showToast(getResources().getString(R.string.string63));
            return;
        }

        if (!Utils.isMobileNO(phoneNumber)) {
            return;
        }

        if (!Utils.everyPaw(passWord)) {
            return;
        }

        if (!Utils.sdIsOk()) {
            return;
        }

        if (!hasPermission) {

            hasPermission();
            return;
        }


        login(phoneNumber, passWord);
    }

    private void login(final String phoneNumber, final String passWord) {
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", phoneNumber);
        map.put("pwd", passWord);

        String json = GsonUtil.parseMapToJson(map);
        showProgrees(getResources().getString(R.string.string61));
        OkHttpUtils
                .postString()
                .url(UriContect.LOGIN)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(getResources().getString(R.string.string58));
                        hideProgree();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        LoginBeen been = GsonUtil.parseJsonToBean(response, LoginBeen.class);
                        MacErrBeen errBeen = GsonUtil.parseJsonToBean(response, MacErrBeen.class);
                        if (been == null) {
                            if (errBeen != null) {
                                ToastMake.showToast(errBeen.getMsg());
                            }
                            return;
                        }
                        if (!TextUtils.equals(been.getError_code(), "0")) {
                            ToastMake.showToast(been.getMsg());
                            return;
                        } else {
//                            ToastMake.showToast(been.getMsg());
                            CompontApplayCation.phone = phoneNumber;
                            if (been.getData().getNickname() != null && !TextUtils.isEmpty(been.getData().getNickname())) {
                                Utils.setString(been.getData().getNickname(), ContectUtils.NICKNAME);
                            }
                            if (been.getData().getPortrait_img() != null && !TextUtils.isEmpty(been.getData().getPortrait_img())) {
                                Utils.setString(been.getData().getPortrait_img(), ContectUtils.IMAGEICONURI);
                            }
                            //如果状态是1表示尚未完成车辆信息
                            Utils.setString(been.getData().getStatus(), ContectUtils.STATUS);
                            if (TextUtils.equals("1", been.getData().getStatus())) {
                                ToastMake.showToast("该号码尚未注册");
                                return;
                            } else if (TextUtils.equals("2", been.getData().getStatus())) {
                                //如果注册了没有了注册汽车
//                                startActivity(new Intent(LoginActivity.this, BasicInfoActivity.class));
                                saveMessage(phoneNumber, passWord);
                                skipOtherActivity(BasicInfoActivity.class, true);
                                return;
                            }
//                            else if () {
//                                //如果车辆状态是2，表示尚未扫码
//                                //如果没有扫描完。进入扫描界面
////                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
//                                saveMessage(phoneNumber, passWord);
//                                Utils.setString(phoneNumber, ContectUtils.PHONESAVE);
//                                skipOtherActivity(BundingSetActivity.class,false);
//                                return;
//                            }
                            else if (TextUtils.equals("4", been.getData().getStatus()) || TextUtils.equals("3", been.getData().getStatus())) {
                                //表示全部完成
                                saveMessage(phoneNumber, passWord);
//                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                //进入主界面的时候,清空所有的任务栈
                                skipOtherActivity(MainActivity.class, true);
                                return;
                            } else {
                                //如果有其他的，表示再加入扫码座椅
                                saveMessage(phoneNumber, passWord);
//                                startActivity(new Intent(LoginActivity.this, ChioceSetActivity.class));
                                skipOtherActivity(ChioceSetActivity.class, false);
                                return;
                            }
                        }
                    }
                });
    }

    private void saveMessage(String phoneNumber, String passWord) {
        //保存账号跟密码
        if (Utils.sdIsOk() || hasPermission) {
            PasswordNameSave.savePassword(LoginActivity.this, phoneNumber, passWord, true);
        }
        CompontApplayCation.phone = phoneNumber;
        //本地sp保存一下
        Utils.setString(phoneNumber, ContectUtils.PHONESAVE);
        Utils.setString(passWord, ContectUtils.PASSWORLD);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN && CompontApplayCation.loginNeedFinsh) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMake.showToast(getResources().getString(R.string.string28));
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getInstance().appExit();
                finish();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
